﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xinkui.Common.Enum;
using CommonFramework.Utility;
using CommonFramework.Attach;
using System.IO;

namespace Xinkui.Common {
    public class FileBase {
        /// <summary>
        /// 通过文件名及类型，生成浏览路径
        /// </summary>
        /// <param name="fileName">000 000 123.jpg</param>
        /// <param name="sType"></param>
        /// <returns></returns>
        public static string GetDirectoryPath(string fileName, ESourceType sType) {
            if (string.IsNullOrEmpty(fileName)) {
                return string.Empty;
            }

            FileSettingEntity fsEntity = FileManger.GetFileSetting((int)sType);

            string filePath = GetPathByfileName(fileName);

            return fsEntity.FilePath + filePath;

        }


        /// <summary>
        /// 通过附件ID 生成完整路径
        /// </summary>
        /// <param name="attachmentID"></param>
        /// <returns></returns>
        public static string GetDirectoryPath(int attachmentID, ESourceType sType, string fileExtension) {
            if (attachmentID <= 0) {
                throw new Exception("附件ID必须大于零");
            }

            FileSettingEntity fsEntity = FileManger.GetFileSetting((int)sType);

            if (fsEntity == null) {
                throw new Exception("无此类型的文件配置，类型名：" + sType.ToString());
            }

            string fileName = GetPathByAttachmentID(attachmentID, fileExtension);

            string allPath = System.Web.HttpContext.Current.Server.MapPath(fsEntity.FilePath + fileName);

            string directPath = Path.GetDirectoryName(allPath);

            if (!Directory.Exists(directPath)) {
                Directory.CreateDirectory(directPath);
            }

            return allPath;
        }


        /// <summary>
        /// 将附件ID转换为String类型 长度9
        /// </summary>
        /// <param name="attachmentID">附件9</param>
        /// <returns></returns>
        private static string IntConverntString(int attachmentID) {
            return attachmentID.ToString("D9");
        }

        /// <summary>
        /// 将附件ID转换为String类型 长度9
        /// </summary>
        /// <param name="attachmentID">附件9</param>
        /// <returns></returns>
        private static string IntConverntString(string attachmentID) {
            int attID = 0;
            Int32.TryParse(attachmentID, out attID);

            return attID.ToString("D9");
        }

        private static string GetPathByfileName(string fileName) {
            return IntConverntString(Path.GetFileNameWithoutExtension(fileName)).SplitString(3).JoinBy("/") + Path.GetExtension(fileName);
        }

        private static string GetPathByAttachmentID(int attachmentID, string fileExtension) {
            return IntConverntString(attachmentID).SplitString(3).JoinBy("/") + fileExtension;
        }
    }
}
